package com.nowcoder.community.controller;

import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.RegisterService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Map;

@Controller
public class RegisterController {

    @Autowired
    private RegisterService registerService;

    // 获取注册页面
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String getRegisterPage() {
        return "/site/register";
    }

    // 注册
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(Model model, User user) {
        Map<String, Object> map = registerService.register(user);
        if (map == null || map.isEmpty()) {
            // 注册成功
            model.addAttribute("msg", "注册成功,我们已经向您的邮箱发送了一封激活邮件,请尽快激活!");
            model.addAttribute("target", "/index");
            return "/site/operate-result";
        } else {
            // 注册失败
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            model.addAttribute("emailMsg", map.get("emailMsg"));
            return "/site/register";
        }
    }

    // 激活
    @RequestMapping(value = "/activation/{userId}/{code}", method = RequestMethod.GET)
    public String activate(@PathVariable("userId") int userId, @PathVariable("code") String code, Model model) {
        int result = registerService.activate(userId, code);
        if (result == CommunityConstant.ACTIVATE_SUCCESS) {
            model.addAttribute("msg", "激活成功，即将前往登录页面。");
            model.addAttribute("target", "/login");
        } else if (result == CommunityConstant.ACTIVATE_REPEAT) {
            model.addAttribute("msg", "帐号已激活过，无需再次激活，即将前往登录页面。");
            model.addAttribute("target", "/login");
        } else if (result == CommunityConstant.ACTIVATE_FAILURE) {
            model.addAttribute("msg", "激活失败，即将前往首页。");
            model.addAttribute("target", "/index");
        }
        return "/site/operate-result";
    }



}
